/**
 * Copyright (c) 2005-2012 https://github.com/zhangkaitao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.tar.commons.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.tar.commons.web.model.SystemContext;

/**
 * 设置通用数据的Interceptor
 * <p>User: 杨浩泉
 * <p>Date: 2015-4-23
 * <p>Version: 1.0
 */
public class SetCommonDataInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //设置排序参数
        setSortParams(request);

        return true;
    }
    
    @Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    	SystemContext.removeOrder();
    	SystemContext.removeOrderby();
    	SystemContext.removePage();
    	SystemContext.removePageIndex();
    	SystemContext.removePageNumber();
    	SystemContext.removePageSize();
    	SystemContext.removeRows();
		SystemContext.removeSort();
		
		super.afterCompletion(request, response, handler, ex);
	}

    public void setSortParams(HttpServletRequest request) {
    	String sort = request.getParameter("sort") ;
		String order = request.getParameter("order") ;
		String orderby = request.getParameter("orderby") ;
		
		if(null != sort && !"".equals(sort))
			SystemContext.setSort(sort);
		
		if(null != order && !"".equals(order))
			SystemContext.setOrder(order);
		
		if(null != orderby && !"".equals(orderby))
			SystemContext.setOrderby(orderby);
    }
    

}
